# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "人保寿险关爱百万（孝心版）医疗保险"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(40, 71)],
            # 有无社保
            "socialSec": ["Y"],
            # 保障期限
            "expire": ["1年"],
            # 交费方式
            "payType": ["年交"],
            # 赔付比率
            "payRate": ["100%"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["expire"], plan["payType"], plan["payRate"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self,dt=None):

        data = {"header": {"transRefGUID": "1231234342356767878", "transDate": "2017-8-14", "transTime": "11:29:00",
                           "businessType": "001"}, "body": {"combCode": "GABWXXBYLBX", "policyType": "1",
                                                            "inputFactors": {"age": dt["year"], "insuYear": "1Y",
                                                                             "memoSpec": "", "socialSecurity": "Y",
                                                                             "amnt": "200", "birth": "1951-03-18",
                                                                             "combcode": "GABWXXBYLBX",
                                                                             "organid": "-1"}, "addRisks": []}}

        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.json()["msg"]:
            price = Helper.decimalParse( r.json()["data"]["mainPrem"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)



